package com.atguigu.tingshu.order.context;

import com.atguigu.tingshu.order.interceptor.OrderHandlerInterceptor;
import com.atguigu.tingshu.vo.order.OrderInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

/**
 * Author  王东剑
 * Created on 23/6/2024 PM12:29
 * Package_name com.atguigu.tingshu.order.context
 * Description
 */
@Component
@Slf4j
public class OrderHandlerInterceptorContext implements ApplicationContextAware {
	public static List<OrderHandlerInterceptor> orderHandlerInterceptorList = new CopyOnWriteArrayList<>();

	/**
	 * 提供责任链入口方法,用于处理
	 * 1.校验数据是否被篡改 ValidDataOrderHandlerInterceptor
	 * 2.校验订单是否重复 OrderRepeatSubmitValidOrderHandlerInterceptor
	 * 3.保存订单到本地 SavaOrderOrderHandlerInterceptor
	 * @param orderInfoVo 前端传来的信息
	 * @return orderInfoVo
	 */
	public static OrderInfoVo entry(OrderInfoVo orderInfoVo){
		for (OrderHandlerInterceptor orderHandlerInterceptor : orderHandlerInterceptorList) {
			orderInfoVo = orderHandlerInterceptor.submitOrderRequestProcess(orderInfoVo);
		}
		return orderInfoVo;
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		Map<String, OrderHandlerInterceptor> beansOfType = applicationContext.getBeansOfType(OrderHandlerInterceptor.class);
		beansOfType
				.values()
				.stream()
				.sorted(Comparator.comparingInt(OrderHandlerInterceptor::sort))
				.forEach(orderHandlerInterceptorList::add);
		log.info("提交订单责任链任务列表初始化完成............");
	}
}
